package com.qf.emp.controller;

import com.alibaba.fastjson.JSON;
import com.qf.emp.constants.BaseConstants;
import com.qf.emp.entity.Dept;
import com.qf.emp.service.IDeptService;
import com.qf.emp.service.impl.DeptServiceImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@WebServlet("/DeptServlet/*")
public class DeptServlet extends BaseServlet {

    private IDeptService deptService = new DeptServiceImpl();

    public void list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取所有的部门
        List<Dept> deptlist = deptService.list();

        // 2.转成JSON数据
        String json = JSON.toJSONString(deptlist);
        // 3.响应出去
        resp.getWriter().write(json);

    }

    public void alist(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取所有的部门
        List<Dept> deptlist = deptService.list();

        req.setAttribute("deptlist", deptlist);
        req.getRequestDispatcher("/dept/deptList.jsp").forward(req,resp);

    }


    // 这个方法最终返回的JSON数据
    public String addDeptAsync(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取前端传递的数据
        String text = req.getReader().readLine();
        // 2.把JSON转成对象
        Dept t = JSON.parseObject(text, Dept.class);
        // 3.入库
        boolean save = deptService.save(t);
        // 4.响应
        return outJson(save);
    }
    public String updateDeptAsync(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取前端传递的数据
        String text = req.getReader().readLine();
        // 2.把JSON转成对象
        Dept t = JSON.parseObject(text, Dept.class);
        // 3.入库
        boolean save = deptService.update(t);
        // 4.响应
        return outJson(save);
    }


    public String removeDept(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        // 1.获取删除的id
        String deptno = req.getParameter("deptno");
        // 2.调用业务层删除
        return outRedirect(deptService.remove(Integer.parseInt(deptno)), "DeptServlet/alist");
    }

    public String getDeptById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 1.获取需要查询的员工编号
        String deptno = request.getParameter("deptno");
        // 2.调用业务层查询
        Dept dept = deptService.byId(Integer.parseInt(deptno));
        // 3.把数据放到域对象中
        request.setAttribute("dept", dept);
        // 4.跳转到jsp
        return BaseConstants.BASE_FORWARD + ":" + "dept/updateDept.jsp";
    }
}
